package pencil.controller;

import java.sql.SQLException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pencil.service.pencil_service;
import pencil.to.cuttingMachineTO;
import pencil.to.paintingMachineTO;
import pencil.to.pencilTO;
import pencil.util.pencilUtil;

//
/**
 * semiPencil을 페인팅 처리 및 마무리
 * 그다음 완성된 연필을 5개씩 연필 완성품 DB에 넣는다.
 * 
 */
@Controller
@RequestMapping("/paintingMachine")
public class paintingMachineController {
private pencil_service service;
	
	public void setService(pencil_service service){
		this.service= service;
	}
	
	@RequestMapping("/begin.do")
	public ModelAndView begin(int orderNumS) throws SQLException, InterruptedException{
		//0. 주문량에 필요한 재료계산
		int semipencil=orderNumS;
		int normal=0;//성공된 제품의수
		int abnormal=0;//비정상 품
//		기계상태 가져오기
		paintingMachineTO pmto = service.selectPaintingMInfo();
		
		if(pmto==null){
			pmto = new paintingMachineTO();
		}
		
		int machineLife = pmto.getMachineLife();
		
		System.out.println("재료 공정 시작");
		
		
		
//		hmto.setBoard(namuNeed);
		pmto.setRunstep(0);
		
		
		pmto.setStartTime(pencilUtil.getNow());//시작시간
		
		int run = 0;
		while(run<=5){
			
			
			//작동시간//
			Thread.sleep(1000);
			//
			pmto.setRunstep(run++);
			System.out.println("진행률:"+(int)pmto.getRunstep());
		}	
		
		pmto.setEndTime(pencilUtil.getNow());
		int testValue=pencilUtil.troubleMaker(5, 5);//불량률 조절 매서드(기본값, 랜덤값)
	//		System.out.println("불량률:"+testValue );
		
		if(testValue>=7){//불량률 판별
			normal=normal+1;//성공품 증가
			
		}else{
			abnormal=abnormal+1;
				
		}
			
		machineLife++;
			
			
			
		pmto.setSemiPencil(semipencil);
		pmto.setNormal(normal);
		pmto.setMachineLife(machineLife);
		pmto.setAbnormal(abnormal);
		
//		    불량처리해야함	
			if(abnormal==0){
				pmto.setState("정상");
			}else{
				pmto.setState("불량");
			}
			
			

			System.out.println("세미연필 개수 : " + orderNumS);
			System.out.println("정상품 개수 " + normal);
			System.out.println("불량품 개수 " + abnormal);
			
		
	
			service.insertPaintingMInfo(pmto);
			
			
//			완성된 연필 창고에 넣기
//			먼저 창고에서 재고양을 select해서  더한 후 insert
			pencilTO pto = service.selectPencil();
			
			if(pto==null){
				pto = new pencilTO();
			}
			
			pto.setDateRegist(pencilUtil.getNow());
			pto.setInvenInfo("입고");
			pto.setCount(pto.getCount() + 5);
		
			service.insertPencil(pto);
	
		
	
		
	return null;
			
	}
	
	
}
